<?php

class UserAuth
{
    public static $uidKey = 'PAUTH';

    public static function setAuth($mobile)
    {
        //保存登录信息到cookie
        $config = Yaf_Registry::get("config")->cookie;
        $now = time();
        $txt = dechex($mobile) . '|' . dechex($now);
        $clientKey = TokenAuthConfig::getClientKey();
        $uid = GenerateEncrypt::encrypt($txt, $clientKey['user'] . self::loginKey());
        setcookie('PUSER', $uid, time() + 3600 * 2, '/', $config['domain']);
        setcookie('mobile', $mobile);
        return $uid;
    }

    public static function getAuth()
    {
        $uid = $_COOKIE['PUSER'];
        $clientKey = TokenAuthConfig::getClientKey();
        $adminStr = GenerateEncrypt::decrypt($uid, $clientKey['user'] . self::loginKey());
        $admin = explode('|', $adminStr);

        if (!empty($admin) && isset($admin[1]))
            return $admin;
        else
            return null;
    }

    public static function delAuth()
    {
        $config = Yaf_Registry::get("config")->cookie;
        setcookie('PUSER', '', time() - 60 * 60 * 24 * 365, '/', $config['domain']);
        setcookie('random_key', '', time() - 60 * 60 * 24 * 365, '/', $config['domain']);
    }

    private static function loginKey()
    {
        $key = "";
        if (getenv('RUNTIME_ENVIROMENT') == 'rls') {
            $config = Yaf_Registry::get("config")->logon;
            if (!empty($config)) {
                return $config['key'];
            }
        }
        return "";
    }
}
